<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="申请单号" prop="applyId">
        <el-input
          v-model="queryParams.applyId"
          placeholder="请输入申请单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经办人" prop="workStaffName">
        <el-input
          v-model="queryParams.workStaffName"
          placeholder="请输入经办人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable size="small">
          <el-option
            v-for="dict in auditStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="申请单号" align="center" prop="applyId"/>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus==2" style="color: red">已驳回</span>
          <span v-if="scope.row.auditStatus==1" style="color: red">审核通过</span>
          <span v-if="scope.row.auditStatus==0" style="color: red">待审核</span>
        </template>
      </el-table-column>
      <el-table-column label="审核意见" align="center" prop="reason"/>
      <el-table-column label="经办人" align="center" prop="workStaffName"/>
      <el-table-column label="经办人电话" align="center" prop="workTel"/>
      <el-table-column label="车间主任" align="center" prop="workLeaderName"/>
      <el-table-column label="科室分管人员" align="center" prop="deptStaffName"/>
      <el-table-column label="科室负责人" align="center" prop="deptLeaderName"/>
      <el-table-column label="分管领导" align="center" prop="leaderName"/>
      <!--      <el-table-column label="创建人" align="center" prop="createBy" />-->
      <!--      <el-table-column label="创建时间" align="center" prop="createTime" />-->
      <!--      <el-table-column label="修改人" align="center" prop="updateBy" />-->
      <!--      <el-table-column label="修改时间" align="center" prop="updateTime" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleApply(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.auditStatus==2"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 修改申请单对话框 -->
    <el-dialog :title="applyDialogTitle" :visible.sync="applyDialog" width="900px">
      <el-form class="scform" ref="applyForm" :model="applyForm" :rules="applyRules" label-width="120px"
               style="width:100%;display: flex;flex-direction: row;flex-wrap: wrap"
      >
<!--        <el-form-item label="车间主任" prop="workLeader">-->
<!--          <el-select v-model="applyForm.workLeader" placeholder="审批人" clearable size="small">-->
<!--            <el-option-->
<!--              v-for="dict in workLeader"-->
<!--              :key="dict.userId"-->
<!--              :label="dict.nickName"-->
<!--              :value="dict.userId"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="选择科室审核人">-->
<!--          <el-cascader-->
<!--            v-model="selectedOptions"-->
<!--            :options="options2"-->
<!--            :props="{-->
<!--    value: 'userId',-->
<!--    label: 'nickName',-->
<!--    children: 'auditor'-->
<!--  }" @change="handleChange"-->
<!--          ></el-cascader>-->
<!--        </el-form-item>-->
        <el-form-item label="经办人电话" prop="workTel">
          <el-input v-model="applyForm.workTel" placeholder="请输入经办人电话" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="送报时间" prop="applyTime">
          <el-date-picker
            v-model="applyForm.applyTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
            align="right"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-table :data="selectedRecords">
        <el-table-column label="废旧物资名称" align="center" prop="goodsName"/>
        <el-table-column label="规格型号" align="center" prop="goodsSpec"/>
        <el-table-column label="数量" align="center" prop="goodsNum"/>
        <el-table-column label="计量单位" align="center" prop="goodsUnit"/>
        <el-table-column label="重量（千克）" align="center" prop="weight"/>
        <el-table-column label="单价">
          <template slot-scope="scope">
            <el-input v-model="scope.row.unitPrice" placeholder="请输入单价"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="提货地点">
          <template slot-scope="scope">
            <el-input v-model="scope.row.place" placeholder="请输入提货地点"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="科室意见">
          <template slot-scope="scope">
            <el-input v-model="scope.row.idea" placeholder="请输入科室意见" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="selectedRecordsDelete(scope.row.index)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="detail" style="margin-top: 20px;">
        <div class="itmName">
          分管领导： {{ applyForm.leaderName }}
          <img :src="applyForm.leaderSign" class="img" v-if="applyForm.leaderSign"/>
        </div>
        <div class="itmName">
          业务科室负责人： {{ applyForm.deptLeaderName }}
          <img :src="applyForm.deptLeaderSign" class="img" v-if="applyForm.deptLeaderSign"/>
        </div>
        <div class="itmName">
          业务科室分管人员： {{ applyForm.deptStaffName }}
          <img :src="applyForm.deptStaffSign" class="img" v-if="applyForm.deptStaffSign"/>
        </div>
        <div class="itmName">
          车间主任： {{ applyForm.workLeaderName }}
          <img :src="applyForm.workLeaderSign" class="img" v-if="applyForm.workLeaderSign"/>
        </div>
        <div class="itmName">
          经办人： {{ applyForm.workStaffName }}
          <img :src="applyForm.workStaffSign" class="img" v-if="applyForm.workStaffSign"/>
        </div>
        <div class="itmName">
          联系电话： {{ applyForm.workTel }}
        </div>
      </div>
      <div class="sign-canvas">
        <div>电子签名处：</div>
        <sign-canvas style="display: block;" ref="SignCanvas" v-model="sign"/>
        <div style="display: flex;flex-direction: column;justify-content: end;height: 300px;margin-left: 10px;">
          <el-button type="primary" plain @click="canvasClear">重新签名</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApplyForm" :loading="applyLoading">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 申请单详情对话框 -->
    <el-dialog :title="applyTitle" :visible.sync="detailDialog" width="900px">
      <div class="detail">
        <!--        <div class="itm">审批人： {{ applyInfo.nextAudit }}</div>-->
        <div class="itm">经办人电话： {{ applyInfo.workTel }}</div>
        <div class="itm">送报时间： {{ applyInfo.applyTime }}</div>
        <div class="itm">审核意见: {{ applyInfo.reason ?applyInfo.reason : ''}}</div>
      </div>
      <el-table v-loading="loading" :data="applyInfo.details">
        <el-table-column label="废旧物资名称" align="center" prop="goodsName"/>
        <el-table-column label="规格型号" align="center" prop="goodsSpec"/>
        <el-table-column label="数量" align="center" prop="goodsNum"/>
        <el-table-column label="计量单位" align="center" prop="goodsUnit"/>
        <el-table-column label="重量（千克）" align="center" prop="weight"/>
        <el-table-column label="单价" align="center" prop="unitPrice"/>
        <el-table-column label="提货地点" align="center" prop="place"/>
        <el-table-column label="科室意见" align="center" prop="idea"/>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
      <DownFile :file="applyInfo.ideaFile"></DownFile>
      <div class="detail" style="margin-top: 20px;">
        <div class="itmName">
          分管领导： {{ applyInfo.leaderName }}
          <img :src="applyInfo.leaderSign" class="img" v-if="applyInfo.leaderSign"/>
        </div>
        <div class="itmName">
          业务科室负责人： {{ applyInfo.deptLeaderName }}
          <img :src="applyInfo.deptLeaderSign" class="img" v-if="applyInfo.deptLeaderSign"/>
        </div>
        <div class="itmName">
          业务科室分管人员： {{ applyInfo.deptStaffName }}
          <img :src="applyInfo.deptStaffSign" class="img" v-if="applyInfo.deptStaffSign"/>
        </div>
        <div class="itmName">
          车间主任： {{ applyInfo.workLeaderName }}
          <img :src="applyInfo.workLeaderSign" class="img" v-if="applyInfo.workLeaderSign"/>
        </div>
        <div class="itmName">
          经办人： {{ applyInfo.workStaffName }}
          <img :src="applyInfo.workStaffSign" class="img" v-if="applyInfo.workStaffSign"/>
        </div>
        <div class="itmName">
          联系电话： {{ applyInfo.workTel }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDetailForm">确定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApply, getPost, delApply, addPost, updatePost, applyInfo, auditorList, addApply } from '@/api/system/scrap'
import SignCanvas from '../components/signCanvas'
import DownFile from '../components/downFile'
import { listData } from '@/api/system/dict/data'

export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  components: { SignCanvas ,DownFile},
  data() {
    return {
      auditStatusList:[
        { label: '待审核', value: '0'},
        { label: '审核通过', value: '1'},
        { label: '已驳回', value: '2'}
      ],
      options:{
        isFullScreen: false,   ////是否全屏手写 [Boolean] 可选
        isFullCover: false, //是否全屏模式下覆盖所有的元素 [Boolean]   可选
        isDpr: false,       //是否使用dpr兼容高分屏 [Boolean] 可选
        lastWriteSpeed: 1,  //书写速度 [Number] 可选
        lastWriteWidth: 2,  //下笔的宽度 [Number] 可选
        lineCap: 'round',   //线条的边缘类型 [butt]平直的边缘 [round]圆形线帽 [square]	正方形线帽
        lineJoin: 'bevel',  //线条交汇时边角的类型  [bevel]创建斜角 [round]创建圆角 [miter]创建尖角。
        canvasWidth: 350, //canvas宽高 [Number] 可选
        canvasHeight: 370,  //高度  [Number] 可选
        isShowBorder: true, //是否显示边框 [可选]
        bgColor: '#fcc', //背景色 [String] 可选
        borderWidth: 1, // 网格线宽度  [Number] 可选
        borderColor: "#ff787f", //网格颜色  [String] 可选
        writeWidth: 5, //基础轨迹宽度  [Number] 可选
        maxWriteWidth: 30, // 写字模式最大线宽  [Number] 可选
        minWriteWidth: 5, // 写字模式最小线宽  [Number] 可选
        writeColor: '#101010', // 轨迹颜色  [String] 可选
        isSign: true, //签名模式 [Boolean] 默认为非签名模式,有线框, 当设置为true的时候没有任何线框
        imgType:'png'   //下载的图片格式  [String] 可选为 jpeg  canvas本是透明背景的
      },
      applyLoading:false,
      selectedOptions: [],
      options2: [],
      workLeader: [],
      sign: '',
      applyDialogTitle: '',
      applyInfo: {}, // 申请单详情
      applyForm: {},
      sourceList: [],
      disposeList: [],
      delivererList: [],
      receiverList: [],
      scrapShiftList: [],
      operatorList: [],
      applyTitle: '填写报废物资处置申请单',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectedRecords: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      applyDialog: false,
      detailDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyId: '',
        workStaffName: ''
      },
      applyId: '',
      // 表单参数
      form: {},
      // 申请单表单校验
      applyRules: {
        nextAudit: [
          { required: true, message: '审批人不能为空', trigger: 'blur' }
        ],
        workTel: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ],
        applyTime: [
          { required: true, message: '送报时间不能为空', trigger: 'blur' }
        ]
      },
      auditList: [],
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '废旧物资名称不能为空', trigger: 'blur' }
        ],
        goodsSpec: [
          { required: true, message: '规格型号不能为空', trigger: 'blur' }
        ],
        goodsNum: [
          { required: true, message: '数量不能为空', trigger: 'blur' }
        ],
        goodsUnit: [
          { required: true, message: '计量单位不能为空', trigger: 'blur' }
        ],
        source: [
          { required: true, message: '撤旧来源不能为空', trigger: 'blur' }
        ],
        originalUse: [
          { required: true, message: '原安装使用处所不能为空', trigger: 'blur' }
        ],
        warehouse: [
          { required: true, message: '收入仓库名称不能为空', trigger: 'blur' }
        ],
        dispose: [
          { required: true, message: '处置方式不能为空', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '重量不能为空', trigger: 'blur' }
        ],
        scrapClass: [
          { required: true, message: '送废班组不能为空', trigger: 'blur' }
        ],
        scrapTime: [
          { required: true, message: '送废时间不能为空', trigger: 'blur' }
        ],
        receiver: [
          { required: true, message: '收料人不能为空', trigger: 'blur' }
        ],
        deliverer: [
          { required: true, message: '交料人不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  // watch: {
  //   "applyInfo" (val) {
  //     if (val.nextAudit) {
  //       this.auditList = val.nextAudit.split(',')
  //     }
  //   },
  // },
  methods: {
    /**
     * 清除画板
     */
    canvasClear() {
      this.$refs.SignCanvas.canvasClear()
      this.sign = ''
    },

    /**
     * 保存图片
     */
    saveAsImg() {
      this.sign = this.$refs.SignCanvas.saveAsImg()
      // alert(`image 的base64：${img}`)
    },
    submitApplyForm: function() {
      this.applyLoading = true
      this.$refs['applyForm'].validate(valid => {
        if (valid) {
          this.sign = this.$refs.SignCanvas.saveAsImg()
          if (this.sign) {
            for (let i = 0; i < this.selectedRecords.length; i++) {
              if (!this.validateField(this.selectedRecords[i])) {
                return false
              }
            }
            this.applyForm.sign = this.sign
            this.applyForm.details = this.selectedRecords
            // this.applyForm.deptStaff = this.selectedOptions[0]
            // this.applyForm.deptLeader = this.selectedOptions[1]
            // this.applyForm.leader = this.selectedOptions[2]
            if (this.applyForm.applyId != undefined) {
              addApply(this.applyForm).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.canvasClear()
                this.applyDialog = false
                this.getList()
              })
            } else {
              addApply(this.applyForm).then(response => {
                console.log(this.applyForm)
                this.$modal.msgSuccess('新增成功')
                this.canvasClear()
                this.applyDialog = false
                this.getList()
              })
            }
          } else {
            this.$message.error('请填写您的电子签名')
          }
        }
      })
      this.applyLoading = false
    },
    getLabelByCode(code, list) {
      console.log(code)
      console.log(list)
      const foundLabel = list.find(item => item.dictValue == code)
      return foundLabel ? foundLabel.dictLabel : '未知'
    },
    validateField(row) {
      if (!row.place) {
        this.$message.error('提货地点是必填项')
        return false
      } else {
        // 如果有错误状态，这里可以清除错误提示
        return true
      }
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      listApply(this.queryParams).then(response => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
      // 班次车间
      listData({ dictType: 'scrap_shift' }).then(response => {
        this.scrapShiftList = response.rows
      })
      // 交料人
      listData({ dictType: 'deliverer' }).then(response => {
        this.delivererList = response.rows
      })
      // 收料人
      listData({ dictType: 'receiver' }).then(response => {
        this.receiverList = response.rows
      })
      // 撤旧来源
      listData({ dictType: 'deprecition_source' }).then(response => {
        this.sourceList = response.rows
      })
      // 处置方式
      listData({ dictType: 'dispose_way' }).then(response => {
        this.disposeList = response.rows
      })
    },
    // 查询审核人列表
    getAuditList() {
      auditorList({ applyId: this.applyId }).then(response => {
        auditorList({ applyId: this.applyId }).then(response => {
          // this.auditList = response.data
          const { userId, nickName, deptName, postName, workLeader, deptStaff, deptLeader, leader } = response.data
          this.userId = userId
          this.nickName = nickName
          this.deptName = deptName
          this.postName = postName
          this.workLeader = workLeader
          this.deptStaff = deptStaff
          this.deptLeader = deptLeader
          this.leader = leader
          this.options2 = response.data.deptStaff
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.applyDialog = false
      this.detailDialog = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.applyForm = {
        nextAudit: undefined,
        workTel: undefined,
        applyTime: undefined
      }
      this.resetForm('form')
      this.resetForm('applyForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.ids = selection.map(item => item.applyId)
      this.selectedRecords = selection
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加废旧物资回收入库记录单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const applyId = row.applyId
      this.applyId = applyId
      this.applyDialog = true
      // this.getAuditList()
      // 获取详情
      applyInfo({ applyId: applyId }).then(response => {
        this.applyForm = response.data
        this.applyDialogTitle = '修改报废物资处置申请单'
        this.selectedRecords = response.data.details
      })
    },
    selectedRecordsDelete(indexToRemove){
      this.selectedRecords.splice(indexToRemove, 1)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPost(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    submitDetailForm: function() {
      this.detailDialog = false
    },
    // 填写申请单
    handleApply(row) {
      const applyId = row.applyId
      this.applyId = applyId
      applyInfo({ applyId: applyId }).then(response => {
        this.applyInfo = response.data
        this.detailDialog = true
        this.applyTitle = '报废物资处置申请单详情'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.applyId || this.ids
      this.$modal.confirm('是否确认删除申请单号为"' + postIds + '"的数据项？').then(function() {
        return delApply(postIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/scrap/apply/export', {
        ...this.queryParams
      }, `申请单${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.scform {
  .el-form-item {
    width: 50%;
  }
}

.detail {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .itm {
    width: 50%;
    margin-bottom: 10px;
  }

  .itmName {
    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: nowrap;
    width: 33%;
    margin-top: 20px;
  }

  .img {
    width: 100px;
    height: 50px;
    border: none !important;
    border-color: transparent;
  }
}

.sign-canvas {
  margin-top: 30px;
  display: flex;
  flex-direction: row;
  width: 100%;
}
</style>
